<template>
  <h1>欢迎来到首页</h1>
  <el-table :data="goodslist" style="width: 100%">
    <el-table-column prop="name" label="商品名称" />
    <el-table-column prop="price" label="价格" />
    <el-table-column prop="number" label="数量" />
    <el-table-column prop="address" label="地址" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button plain @click="query.dialogVisible = true, goodsobj = scope.row">修改</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination background layout="prev, pager, next" @current-change="getgoodslist" :page-size="3" :total="query.total" />

  <el-dialog
    v-model="query.dialogVisible"
    title="修改商品"
    width="500"
  >
    <span>
      <el-form :model="goodsobj" label-width="auto" style="max-width: 600px">
        <el-form-item label="商品名字">
          <el-input v-model="goodsobj.name" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="goodsobj.price" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="goodsobj.number" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="goodsobj.address" />
        </el-form-item>
      </el-form>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changegoods">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
</style>

<script setup>
  import {ref, onMounted} from "vue"
  import axios from "axios"

  let goodslist = ref([])

  let query = ref({
    total: 0,
    page: 1,
    dialogVisible: false
  })

  let goodsobj = ref({
    id: "",
    name: "",
    price: "",
    number: "",
    address: "",
  })

  const getgoodslist=(page)=>{
    if(page){
      query.value.page = page
    }
    axios.get(`http://127.0.0.1:8000/new_login/my_goods/?page=${query.value.page}`)
    .then(res=>{
      console.log(res)
      query.value.total = res.data.count
      goodslist.value = res.data.results
    })
  }

  const changegoods=()=>{
    axios.put(`http://127.0.0.1:8000/new_login/my_goods/${goodsobj.value.id}/`, goodsobj.value)
    .then(()=>{
      query.value.dialogVisible = false
      goodsobj.value = {
        id: "",
        name: "",
        price: "",
        number: "",
        address: "",
      }
      getgoodslist()
    })
  }

  onMounted(()=>{
    getgoodslist()
  })

</script>
